package net.hserver.gateway.core.strategy.imp;

import net.hserver.gateway.core.strategy.Chose;
import net.hserver.gateway.core.strategy.ServerNode;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author hxm
 */
public class HashConsistencyStrategy<T> implements Chose<T> {
    private List<ServerNode> hosts;

    private static HashConsistencyStrategy hashConsistencyStrategy;

    private HashConsistencyStrategy() {
    }

    @Override
    public T choseInfo(String ip) {
        int i = ip.hashCode();
        int temp = -1;
        ServerNode serverNode = null;
        for (ServerNode host : hosts) {
            int hashCode = host.getHashCode();
            int abs = Math.abs(i - hashCode);
            if (temp==-1){
                temp=abs;
                serverNode=host;
            }else if (temp>abs){
                temp=abs;
                serverNode=host;
            }
        }
        return (T) serverNode;
    }

    public static <T> HashConsistencyStrategy getInstance(List<T> hosts) {
        if (hashConsistencyStrategy == null) {
            synchronized (RandomStrategy.class) {
                if (hashConsistencyStrategy == null) {
                    hashConsistencyStrategy = new HashConsistencyStrategy();
                }
            }
        }
        hashConsistencyStrategy.hosts = hosts;
        return hashConsistencyStrategy;
    }
}
